import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import {
  Card,
  Table,
  Button,
  Space,
  Typography,
  Input,
  Select,
  Tag,
  Avatar,
  Modal,
  Form,
  message,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  Layout,
} from 'antd';
import {
  EditOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  BarChartOutlined,
  TeamOutlined,
  ExportOutlined,
  SyncOutlined,
  FolderOutlined,
  TableOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { telemetryApi, teamApi } from '../services/api';
import BackendDirectoryTree from '../components/BackendDirectoryTree';
import ViewModeToggle from '../components/ViewModeToggle';
import type { ViewMode, TelemetryPoint } from '../types/telemetry';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface Filters {
  search: string;
  type: 'all' | 'UMA' | 'UKM';
  analysisStatus: 'all' | 'NOT_ANALYZED' | 'ANALYZED' | 'NOT_NEEDED' | 'NEEDS_COLLECTION';
  teamId: string;
  sortBy: 'name' | 'createdAt' | 'updatedAt' | 'analysisStatus';
  sortOrder: 'asc' | 'desc';
  directory: string;
  directory_id?: number;
  expiresAfter: string;
}

const TelemetryPoints: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [points, setPoints] = useState<TelemetryPoint[]>([]);
  const [total, setTotal] = useState(0);
  const [filters, setFilters] = useState<Filters>({
    search: '',
    type: 'all',
    analysisStatus: 'all',
    teamId: 'all',
    sortBy: 'updatedAt',
    sortOrder: 'desc',
    directory: '',
    directory_id: undefined,
    expiresAfter: '',
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
  });
  const [urlParamsProcessed, setUrlParamsProcessed] = useState(false);

  // 防止重复API调用的ref
  const isLoadingRef = useRef(false);
  const teamsLoadingRef = useRef(false);
  const statsLoadingRef = useRef(false);

  // 检查导航状态，自动应用团队过滤
  useEffect(() => {
    const navigationState = location.state as any;
    if (navigationState?.teamFilter) {
      console.log('📋 [TelemetryPoints] 检测到团队过滤（来自导航状态），自动应用:', navigationState);
      setFilters(prev => ({
        ...prev,
        teamId: navigationState.teamFilter,
        search: '',
        type: 'all',
        analysisStatus: 'all'
      }));
      setPagination(prev => ({ ...prev, current: 1 }));

      // 清除导航状态，避免重复应用
      navigate(location.pathname, { replace: true, state: null });
    }
  }, [location.state, navigate]);

  // 编辑状态模态框
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingPoint, setEditingPoint] = useState<TelemetryPoint | null>(null);
  const [editForm] = Form.useForm();

  // 用户团队列表
  const [userTeams, setUserTeams] = useState<any[]>([]);

  // 全量统计数据
  const [globalStats, setGlobalStats] = useState<any>(null);

  // 视图模式相关状态
  const [viewMode, setViewMode] = useState<ViewMode>('table');

  // 加载遥测点数据
  const loadTelemetryPoints = async () => {
    if (isLoadingRef.current) {
      console.log('📋 [TelemetryPoints] 检测到重复调用，跳过请求');
      return;
    }

    console.log('📋 [TelemetryPoints] 开始加载遥测点数据', {
      search: filters.search,
      type: filters.type,
      analysisStatus: filters.analysisStatus,
      teamId: filters.teamId,
      directory: filters.directory,
      directory_id: filters.directory_id,
      page: pagination.current,
      pageSize: pagination.pageSize
    });

    try {
      isLoadingRef.current = true;
      setLoading(true);
      const params: {
        page?: number;
        page_size?: number;
        search?: string;
        type_filter?: 'histogram' | 'enum' | 'ukm_event' | 'ukm_metric' | 'UMA' | 'UKM';
        team_filter?: string;
        analysis_status_filter?: string;
        directory?: string;
        directory_id?: number;
        expires_after_filter?: string;
      } = {
        page: pagination.current,
        page_size: pagination.pageSize,
        search: filters.search || undefined,
        type_filter: filters.type === 'all' ? undefined :
                    filters.type === 'UMA' ? 'histogram' :  // Map UMA to histogram type
                    filters.type === 'UKM' ? 'ukm_event' : undefined, // Map UKM to ukm_event type
        team_filter: filters.teamId === 'all' ? undefined : filters.teamId,
        analysis_status_filter: filters.analysisStatus === 'all' ? undefined : filters.analysisStatus,
        directory: filters.directory || undefined,
        directory_id: filters.directory_id || undefined,
        expires_after_filter: filters.expiresAfter || undefined,
      };

      const response = await telemetryApi.getTelemetryPoints(params);

      if (response.data) {
        // Convert API data to match TelemetryPoint interface
        // API response structure: {success: true, data: [...], total: number}
        // response.data is already the array, and response.total is the total count
        const dataArray = response.data;

        const convertedPoints = dataArray.map((item: any): TelemetryPoint => ({
          pointId: item.id.toString(),
          name: item.name,
          telemetryType: item.type === 'histogram' ? 'UMA' : 'UKM',
          sourceFile: item.file_path,
          description: item.description,
          teamId: item.assigned_team_id || undefined,
          teamName: item.assigned_team_name || undefined,
          analysisStatus: (item.analysis_status || 'NOT_ANALYZED') as TelemetryPoint['analysisStatus'],
          analysisNotes: item.analysis_notes,
          createdAt: new Date().toISOString(), // TODO: Get from API
          updatedAt: new Date().toISOString(), // TODO: Get from API
          analyzedBy: item.analyzed_by,
          analyzedAt: item.analyzed_at,
        }));

        // 去重：根据ID和名称确保唯一性
        const uniquePoints = convertedPoints.filter((point, index, arr) =>
          arr.findIndex(p => p.pointId === point.pointId) === index
        );

        console.log(`📋 [TelemetryPoints] 原始数据: ${convertedPoints.length}, 去重后: ${uniquePoints.length}`);
        setPoints(uniquePoints);
        setTotal((response as any).total || 0);
      } else {
        setPoints([]);
        setTotal(0);
      }
    } catch (error: any) {
      console.error('Failed to load telemetry points:', error);
      message.error('加载遥测点失败');
    } finally {
      setLoading(false);
      isLoadingRef.current = false;
    }
  }; // 移除useCallback，避免stale closure问题

  // 加载统计数据 (根据directory过滤)
  const loadGlobalStats = useCallback(async () => {
    if (statsLoadingRef.current) {
      console.log('📋 [TelemetryPoints] Stats API已在加载中，跳过重复请求');
      return;
    }

    try {
      statsLoadingRef.current = true;
      const params: any = {};
      // 添加所有过滤参数到stats API
      if (filters.directory) {
        params.directory = filters.directory;
      }
      if (filters.directory_id) {
        params.directory_id = filters.directory_id;
      }
      if (filters.teamId && filters.teamId !== 'all') {
        params.team_id = filters.teamId;
      }
      if (filters.type && filters.type !== 'all') {
        params.type = filters.type;
      }
      if (filters.analysisStatus && filters.analysisStatus !== 'all') {
        params.analysis_status = filters.analysisStatus;
      }
      if (filters.search) {
        params.search = filters.search;
      }
      if (filters.expiresAfter) {
        params.expires_after = filters.expiresAfter;
      }
      const response = await telemetryApi.getTelemetryStats(params);
      if (response && response.data) {
        setGlobalStats(response.data);
        console.log('📊 [TelemetryPoints] 统计数据:', response.data);
      }
    } catch (error) {
      console.error('Failed to load stats:', error);
    } finally {
      statsLoadingRef.current = false;
    }
  }, [filters.directory, filters.directory_id, filters.teamId, filters.type, filters.analysisStatus, filters.search, filters.expiresAfter]);

  // 加载用户团队
  const loadUserTeams = useCallback(async () => {
    if (teamsLoadingRef.current) {
      console.log('📋 [TelemetryPoints] Teams API已在加载中，跳过重复请求');
      return;
    }

    try {
      teamsLoadingRef.current = true;
      const teams = await teamApi.getTeams();
      // 转换数据格式以匹配当前期望的格式
      const formattedTeams = teams.map(team => ({
        teamId: team.id,
        name: team.name,
      }));
      setUserTeams(formattedTeams);
    } catch (error) {
      console.error('Failed to load user teams:', error);
      // 如果API失败，使用空数组作为fallback
      setUserTeams([]);
    } finally {
      teamsLoadingRef.current = false;
    }
  }, []);

  // Parse URL parameters to handle all filter parameters and pagination
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    console.log('🔗 [TelemetryPoints] 解析URL参数:', location.search);

    // 构建新的filters对象
    const newFilters: any = {};
    let paginationUpdated = false;

    // 处理分页参数
    const pageParam = searchParams.get('page');
    const pageSizeParam = searchParams.get('pageSize');

    if (pageParam || pageSizeParam) {
      setPagination(prev => ({
        ...prev,
        current: pageParam ? parseInt(pageParam, 10) : prev.current,
        pageSize: pageSizeParam ? parseInt(pageSizeParam, 10) : prev.pageSize
      }));
      paginationUpdated = true;
    }

    // 处理所有可能的filter参数
    const searchParam = searchParams.get('search');
    if (searchParam) {
      newFilters.search = decodeURIComponent(searchParam);
    }

    const typeParam = searchParams.get('type');
    if (typeParam) {
      newFilters.type = typeParam;
    }

    const analysisStatusParam = searchParams.get('analysisStatus');
    if (analysisStatusParam) {
      newFilters.analysisStatus = analysisStatusParam;
    }

    const teamIdParam = searchParams.get('teamId');
    if (teamIdParam) {
      newFilters.teamId = teamIdParam;
      console.log('🔗 [TelemetryPoints] 发现teamId参数:', teamIdParam);
    }

    const directoryParam = searchParams.get('directory');
    if (directoryParam) {
      newFilters.directory = decodeURIComponent(directoryParam);
    }

    const directoryIdParam = searchParams.get('directory_id');
    if (directoryIdParam) {
      newFilters.directory_id = parseInt(directoryIdParam, 10);
      console.log('🔗 [TelemetryPoints] 发现directory_id参数:', directoryIdParam);
    }

    const expiresAfterParam = searchParams.get('expiresAfter');
    if (expiresAfterParam) {
      newFilters.expiresAfter = decodeURIComponent(expiresAfterParam);
      console.log('🔗 [TelemetryPoints] 发现expiresAfter参数:', expiresAfterParam);
    }

    // 如果有任何filter参数，更新filters状态
    if (Object.keys(newFilters).length > 0) {
      console.log('🔗 [TelemetryPoints] 更新filters状态:', newFilters);
      setFilters(prev => ({
        ...prev,
        ...newFilters
      }));
      // 只有在没有明确分页参数时才重置到第1页
      if (!paginationUpdated) {
        setPagination(prev => ({ ...prev, current: 1 }));
      }
    }

    // 无论是否有URL参数，都标记为已处理，避免阻塞API调用
    setUrlParamsProcessed(true);
  }, [location.search]);

  // 分别处理不同的数据加载，避免相互影响
  // 1. 加载用户团队 - 只在组件挂载时加载一次
  useEffect(() => {
    console.log('🔄 [TelemetryPoints] 加载用户团队');
    loadUserTeams();
  }, []); // 空依赖数组，只在挂载时执行一次

  // 2. 加载遥测点数据 - 依赖过滤条件变化，但不依赖函数引用
  useEffect(() => {
    // 只有在URL参数处理完成后才加载数据
    if (!urlParamsProcessed) {
      console.log('🔄 [TelemetryPoints] URL参数未处理完成，跳过数据加载');
      return;
    }
    console.log('🔄 [TelemetryPoints] 加载遥测点数据');
    loadTelemetryPoints();
  }, [pagination.current, pagination.pageSize, filters.search, filters.type, filters.analysisStatus, filters.teamId, filters.directory, filters.expiresAfter, urlParamsProcessed]);

  // 3. 加载统计数据 - 依赖directory变化和URL处理完成
  useEffect(() => {
    // 只有在URL参数处理完成后才加载统计数据
    if (!urlParamsProcessed) {
      console.log('🔄 [TelemetryPoints] URL参数未处理完成，跳过统计数据加载');
      return;
    }
    console.log('🔄 [TelemetryPoints] 加载统计数据');
    loadGlobalStats();
  }, [loadGlobalStats, urlParamsProcessed]);

  // 处理搜索
  const handleSearch = (value: string) => {
    if (filters.search !== value) {
      setFilters(prev => ({ ...prev, search: value }));
      setPagination(prev => ({ ...prev, current: 1 }));
    }
  };

  // 处理筛选变化
  const handleFilterChange = (key: keyof Filters, value: any) => {
    if (filters[key] !== value) {
      setFilters(prev => ({ ...prev, [key]: value }));
      setPagination(prev => ({ ...prev, current: 1 }));
    }
  };

  // 处理表格变化
  const handleTableChange = (paginationInfo: any, sorter: any) => {
    if (pagination.current !== paginationInfo.current || pagination.pageSize !== paginationInfo.pageSize) {
      setPagination({
        current: paginationInfo.current,
        pageSize: paginationInfo.pageSize,
      });
    }

    if (sorter.field) {
      const newSortOrder = sorter.order === 'ascend' ? 'asc' : 'desc';
      if (filters.sortBy !== sorter.field || filters.sortOrder !== newSortOrder) {
        setFilters(prev => ({
          ...prev,
          sortBy: sorter.field,
          sortOrder: newSortOrder,
        }));
      }
    }
  };

  // 处理分析状态更新
  const handleUpdateAnalysisStatus = async (point: TelemetryPoint, values: any) => {
    // TODO: Implement analysis status update API endpoint
    message.info('分析状态更新功能暂未实现');
    setEditModalVisible(false);
    setEditingPoint(null);
    editForm.resetFields();
  };

  
  // 视图模式切换处理
  const handleViewModeChange = (mode: ViewMode) => {
    console.log('🔄 [TelemetryPoints] 切换视图模式:', mode);
    setViewMode(mode);
  };

  // 键盘分页功能
  const handleKeyDown = useCallback((event: KeyboardEvent) => {
    // 检查是否在输入框或模态框中，如果是则不处理键盘事件
    const target = event.target as HTMLElement;
    if (
      target.tagName === 'INPUT' ||
      target.tagName === 'TEXTAREA' ||
      target.tagName === 'SELECT' ||
      target.contentEditable === 'true' ||
      target.closest('.ant-modal') ||
      target.closest('.ant-select-dropdown')
    ) {
      return;
    }

    // 只处理左右方向键
    if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
      event.preventDefault();

      const totalPages = Math.ceil(total / pagination.pageSize);
      let newPage = pagination.current;

      if (event.key === 'ArrowLeft') {
        // 上一页
        newPage = Math.max(1, pagination.current - 1);
      } else if (event.key === 'ArrowRight') {
        // 下一页
        newPage = Math.min(totalPages, pagination.current + 1);
      }

      // 只有当页码发生变化时才更新
      if (newPage !== pagination.current) {
        setPagination(prev => ({ ...prev, current: newPage }));
      }
    }
  }, [pagination.current, pagination.pageSize, total]);

  // 添加键盘事件监听器
  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [handleKeyDown]);

  // 生成详情页URL，包含当前filter参数和分页参数
  const getDetailPageUrl = (pointId: string) => {
    const searchParams = new URLSearchParams();

    // 添加当前页码参数
    searchParams.set('page', pagination.current.toString());
    searchParams.set('pageSize', pagination.pageSize.toString());

    // 添加当前所有filter参数
    if (filters.search) {
      searchParams.set('search', filters.search);
    }
    if (filters.type !== 'all') {
      searchParams.set('type', filters.type);
    }
    if (filters.analysisStatus !== 'all') {
      searchParams.set('analysisStatus', filters.analysisStatus);
    }
    if (filters.teamId !== 'all') {
      searchParams.set('teamId', filters.teamId);
    }
    if (filters.directory) {
      searchParams.set('directory', filters.directory);
    }
    // 添加directory_id参数支持
    if (filters.directory_id) {
      searchParams.set('directory_id', filters.directory_id.toString());
    }
    if (filters.expiresAfter) {
      searchParams.set('expiresAfter', filters.expiresAfter);
    }

    const queryString = searchParams.toString();
    return queryString ? `/analysis/points/${pointId}?${queryString}` : `/analysis/points/${pointId}`;
  };

  // 树形遥测点选择处理
  const handleTreePointSelect = (point: any) => {
    console.log('🌳 [TelemetryPoints] 选择遥测点:', point);
    navigate(getDetailPageUrl(point.id));
  };

  // 打开编辑模态框
  const openEditModal = (point: TelemetryPoint) => {
    setEditingPoint(point);
    editForm.setFieldsValue({
      analysisStatus: point.analysisStatus,
      analysisNotes: point.analysisNotes,
    });
    setEditModalVisible(true);
  };

  // 获取类型标签
  const getTypeTag = (type: string) => {
    const config = {
      UMA: { color: 'blue', text: 'UMA' },
      UKM: { color: 'green', text: 'UKM' },
    };
    const typeConfig = config[type as keyof typeof config];
    return typeConfig ? <Tag color={typeConfig.color}>{typeConfig.text}</Tag> : null;
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    const config = {
      NOT_ANALYZED: { color: 'orange', text: '待分析', icon: <ClockCircleOutlined /> },
      ANALYZED: { color: 'green', text: '已分析', icon: <CheckCircleOutlined /> },
      NOT_NEEDED: { color: 'default', text: '不需要收集', icon: <CheckCircleOutlined /> },
      NEEDS_COLLECTION: { color: 'red', text: '需要收集', icon: <ExclamationCircleOutlined /> },
    };
    const statusConfig = config[status as keyof typeof config];
    return statusConfig ? (
      <Badge
        status={statusConfig.color as any}
        text={statusConfig.text}
      />
    ) : null;
  };

  
  // 表格列定义
  const columns: ColumnsType<TelemetryPoint> = [
    {
      title: '遥测点名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      render: (text, record) => (
        <Space>
          <Avatar icon={<BarChartOutlined />} size="small" />
          <div>
            <div
              style={{ fontWeight: 500, cursor: 'pointer', color: '#1890ff' }}
              onClick={() => navigate(getDetailPageUrl(record.pointId))}
            >
              {text}
            </div>
            {record.description && (
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {record.description.substring(0, 50)}...
              </Text>
            )}
          </div>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'telemetryType',
      key: 'telemetryType',
      width: 80,
      render: (type) => getTypeTag(type),
    },
    {
      title: '分析状态',
      dataIndex: 'analysisStatus',
      key: 'analysisStatus',
      width: 120,
      sorter: true,
      render: (status) => getStatusTag(status),
    },
    {
      title: '团队',
      dataIndex: 'teamName',
      key: 'teamName',
      width: 120,
      render: (teamName) => (
        <Space>
          {teamName ? (
            <React.Fragment key={`team-${teamName}`}>
              <TeamOutlined />
              <Text>{teamName}</Text>
            </React.Fragment>
          ) : (
            <Text type="secondary">无团队</Text>
          )}
        </Space>
      ),
    },
      ];

  // 统计数据 - 使用全局统计数据，确保显示正确的全局数量
  const stats = {
    total: globalStats?.total_metrics || 0,
    // analyzed状态等于not_needed，不重复计算needs_collection
    analyzed: (globalStats?.by_analysis_status?.not_needed || 0),
    notAnalyzed: globalStats?.by_analysis_status?.not_analyzed || 0,
    needsCollection: globalStats?.by_analysis_status?.needs_collection || 0,
  };

  return (
    <div style={{ maxWidth: 1400, margin: '0 auto', padding: '24px' }}>
      {/* 页面标题 */}
      <Row justify="space-between" align="middle" style={{ marginBottom: '24px' }}>
        <Col>
          <Title level={2} style={{ margin: 0 }}>
            遥测点管理
          </Title>
          <Text type="secondary">
            分析和管理Chrome遥测数据点
          </Text>
        </Col>
        <Col>
          <Space>
            <ViewModeToggle
              currentMode={viewMode}
              onModeChange={handleViewModeChange}
              showLabel={true}
              size="middle"
            />
            <Button icon={<SyncOutlined />} onClick={loadTelemetryPoints}>
              刷新
            </Button>
            <Button icon={<ExportOutlined />}>
              导出数据
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <BarChartOutlined style={{ marginRight: 8, color: '#1890ff' }} />
              <Statistic
                title="总遥测点"
                value={stats.total}
                valueStyle={{ color: '#1890ff' }}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <CheckCircleOutlined style={{ marginRight: 8, color: '#52c41a' }} />
              <Statistic
                title="已分析"
                value={stats.analyzed}
                valueStyle={{ color: '#52c41a' }}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <ClockCircleOutlined style={{ marginRight: 8, color: '#faad14' }} />
              <Statistic
                title="待分析"
                value={stats.notAnalyzed}
                valueStyle={{ color: '#faad14' }}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <ExclamationCircleOutlined style={{ marginRight: 8, color: '#ff4d4f' }} />
              <Statistic
                title="需要收集"
                value={stats.needsCollection}
                valueStyle={{ color: '#ff4d4f' }}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 筛选和搜索 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Input.Search
              placeholder="搜索遥测点名称或描述"
              value={filters.search}
              onChange={(e) => handleSearch(e.target.value)}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Select
              style={{ width: '100%' }}
              value={filters.type}
              onChange={(value) => handleFilterChange('type', value)}
              placeholder="类型"
            >
              <Option value="all">全部类型</Option>
              <Option value="UMA">UMA</Option>
              <Option value="UKM">UKM</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              style={{ width: '100%' }}
              value={filters.analysisStatus}
              onChange={(value) => handleFilterChange('analysisStatus', value)}
              placeholder="分析状态"
            >
              <Option value="all">全部状态</Option>
              <Option value="NOT_ANALYZED">待分析</Option>
              <Option value="NOT_NEEDED">不需要收集</Option>
              <Option value="NEEDS_COLLECTION">需要收集</Option>
            </Select>
          </Col>
          <Col span={3}>
            <Select
              style={{ width: '100%' }}
              value={filters.teamId}
              onChange={(value) => handleFilterChange('teamId', value)}
              placeholder="团队"
            >
              <Option value="all">全部团队</Option>
              {userTeams.map(team => (
                <Option key={team.teamId} value={team.teamId}>
                  {team.name}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={3}>
            <Select
              style={{ width: '100%' }}
              value={filters.expiresAfter}
              onChange={(value) => handleFilterChange('expiresAfter', value)}
              placeholder="过期时间"
            >
              <Option value="">全部</Option>
              <Option value="never">永不过期</Option>
              <Option value="has_expiration">有过期时间</Option>
              <Option value="30d">30天</Option>
              <Option value="90d">90天</Option>
              <Option value="1y">1年</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Space>
              <Text type="secondary">
                共 {total} 条记录
              </Text>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 主要内容区域 - 根据视图模式显示 */}
      {viewMode === 'table' ? (
        /* 表格视图直接显示 */
        null
      ) : (
        /* 树形视图标题 */
        <Card style={{ marginBottom: '16px' }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space>
                <FolderOutlined style={{ fontSize: '18px', color: '#faad14' }} />
                <Text strong style={{ fontSize: '16px' }}>
                  目录树视图
                </Text>
                <Text type="secondary">
                  按文件目录结构组织遥测点，共 {globalStats?.total_metrics || 0} 个遥测点
                </Text>
              </Space>
            </Col>
          </Row>
        </Card>
      )}

      {/* 视图内容 */}
      <Card>
        {viewMode === 'table' && (
          <>
            {/* 键盘快捷键提示 - 移动到表格上方 */}
            {total > pagination.pageSize && (
              <div style={{
                marginBottom: '16px',
                padding: '12px',
                background: '#f0f7ff',
                borderRadius: '6px',
                textAlign: 'center',
                fontSize: '12px',
                color: '#666',
                border: '1px solid #d6e4ff'
              }}>
                <Space>
                  <Text type="secondary" style={{ fontWeight: 500 }}>键盘快捷键:</Text>
                  <Space size="small">
                    <LeftOutlined style={{ fontSize: '12px', color: '#1890ff' }} />
                    <Text keyboard style={{ fontSize: '12px', color: '#1890ff' }}>←</Text>
                    <Text type="secondary">上一页</Text>
                  </Space>
                  <Text type="secondary">|</Text>
                  <Space size="small">
                    <Text keyboard style={{ fontSize: '12px', color: '#1890ff' }}>→</Text>
                    <RightOutlined style={{ fontSize: '12px', color: '#1890ff' }} />
                    <Text type="secondary">下一页</Text>
                  </Space>
                </Space>
              </div>
            )}

            {/* 表格视图 */}
            <Table
              columns={columns}
              dataSource={points}
              rowKey="pointId"
              loading={loading}
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                onChange: (page, pageSize) =>
                  setPagination({ current: page, pageSize: pageSize || 20 }),
              }}
              onChange={handleTableChange}
            />
          </>
        )}

        {viewMode === 'tree' && (
          /* 树形视图 */
          <BackendDirectoryTree
            loading={loading}
            onPointSelect={handleTreePointSelect}
            onPointEdit={(point) => openEditModal({
              pointId: point.id.toString(),
              name: point.name,
              telemetryType: point.type === 'histogram' ? 'UMA' : 'UKM',
              sourceFile: point.file_path,
              description: point.description,
              teamId: point.assigned_team_id || undefined,
              teamName: point.assigned_team_name || undefined,
              analysisStatus: point.analysis_status || 'NOT_ANALYZED',
              analysisNotes: point.analysis_notes,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
              analyzedBy: point.analyzed_by,
              analyzedAt: point.analyzed_at,
            })}
            showStats={true}
            searchable={true}
            height="600px"
            rootPath="tools"
            maxDepth={10}
            includeMetrics={false}
            teamFilter={filters.teamId === 'all' ? undefined : filters.teamId}
            componentFilter={filters.teamId === 'all' ? undefined : undefined}
            typeFilter={
              filters.type === 'all' ? undefined :
              filters.type === 'UMA' ? 'histogram' :
              filters.type === 'UKM' ? 'ukm_event' : undefined
            }
          />
        )}
      </Card>

      {/* 编辑分析状态模态框 */}
      <Modal
        title="编辑分析状态"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setEditingPoint(null);
          editForm.resetFields();
        }}
        footer={null}
      >
        {editingPoint && (
          <Form
            form={editForm}
            layout="vertical"
            onFinish={(values) => handleUpdateAnalysisStatus(editingPoint, values)}
          >
            <Form.Item>
              <Text strong>遥测点：{editingPoint.name}</Text>
            </Form.Item>

            <Form.Item
              label="分析状态"
              name="analysisStatus"
              rules={[{ required: true, message: '请选择分析状态' }]}
            >
              <Select>
                <Option value="NOT_ANALYZED">待分析</Option>
                <Option value="NOT_NEEDED">不需要收集</Option>
                <Option value="NEEDS_COLLECTION">需要收集</Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="分析备注"
              name="analysisNotes"
            >
              <TextArea
                rows={4}
                placeholder="请输入分析备注..."
                maxLength={1000}
                showCount
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
              <Space>
                <Button
                  onClick={() => {
                    setEditModalVisible(false);
                    setEditingPoint(null);
                    editForm.resetFields();
                  }}
                >
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default TelemetryPoints;